package com.bst.common.utils;

import com.bst.common.exception.base.BaseException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateUtil {

    public final static String yyyyMMdd = "yyyyMMdd";

    private final static String[] weekDays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六","星期日"};

    public final static SimpleDateFormat FORMAT_HHMMSS = new SimpleDateFormat("HH:mm:ss");
    public final static SimpleDateFormat FORMAT_YYYY_MM_DD_HHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public final static SimpleDateFormat FORMAT_YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
    public final static SimpleDateFormat FORMAT_YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd");
    public final static SimpleDateFormat FORMAT_YYYY_MM = new SimpleDateFormat("yyyy-MM");

    public static int getWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int i = cal.get(Calendar.DAY_OF_WEEK);
        if(i==1) {
            i = 7;
        } else {
            i = (i-1);
        }
        return i;
    }

    public static String getWeekDes(Date date) {
        return weekDays[getWeek(date)-1];
    }

    /**
     * 线程绑定的日期格式转换器缓存
     */
    private final static ThreadLocal<Map<String, SimpleDateFormat>> dateFormatersCache = new ThreadLocal<Map<String, SimpleDateFormat>>();


    // ======================日期转字符串基础格式化方法======================================================================================

    private static SimpleDateFormat getDateFormater(String format) {
        Map<String, SimpleDateFormat> dateFormaters = dateFormatersCache.get();
        SimpleDateFormat dateFormater = null;
        boolean formatersIsNull = false;

        if (dateFormaters == null) {
            dateFormaters = new HashMap<String, SimpleDateFormat>(3, 0.2f);
            dateFormatersCache.set(dateFormaters);
            formatersIsNull = true;
        }

        if (formatersIsNull || (dateFormater = dateFormaters.get(format)) == null) {
            dateFormater = new SimpleDateFormat(format);
            dateFormaters.put(format, dateFormater);
        }

        return dateFormater;
    }


    public static String toDateStrByFormat(Calendar date, String format) {
        if (date == null) {
            return null;
        }

        return getDateFormater(format).format(date.getTime());
    }


    public static String toDateStrByFormat(Date date, String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return toDateStrByFormat(calendar, format);
    }

    public static Date toDateByFormat(String date, String format) {
        Date parse = null;
        try {
            parse = getDateFormater(format).parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }

    public static Date getDate(String d,Integer euDtDim) throws BaseException {
        Date date = null;
        try {
            switch (euDtDim) {
                case 3: //天
                    date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,8)+" 00:00:00");
                    break;
                case 4: //月
                    date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,6)+"01 00:00:00");
                    break;
                case 5: //季
                    int month = 3*(Integer.parseInt(d.substring(4,5))-1)+1;
                    if(month<12 && month>0) {
                        String sm = month>9?(month+""):("0"+month);
                        date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,4)+sm+"01 00:00:00");
                    }
                    break;
                case 6: //年
                    date = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d.substring(0,4)+"0101 00:00:00");
                    break;
            }
        } catch (Exception e) {
            throw new BaseException("时间格式转换错误");
        }
        if(date==null) {
            throw new BaseException("时间转换失败");
        }
        return date;
    }

    public static Date getNextDate(Date date,Integer euDtDim) throws BaseException {
        Date nextDate = null;
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            switch (euDtDim) {
                case 3: //天
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    break;
                case 4: //月
                    calendar.add(Calendar.MONTH, 1);
                    break;
                case 5: //季
                    calendar.add(Calendar.MONTH, 3);//增加三个月
                    break;
                case 6: //年
                    calendar.add(Calendar.YEAR, 1);
                    break;
            }
            nextDate = new Date(calendar.getTimeInMillis());
        } catch (Exception e) {
            throw new BaseException("时间格式转换错误");
        }
        return nextDate;
    }

    public static Date calculate(Date date,int type,int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(type,num);
        return new Date(calendar.getTimeInMillis());
    }

    public static String getDay(Date date,int type,int num) {
        if(date==null) date = new Date();
        if(num!=0) {
            date = calculate(date,type,num);
        }
        return FORMAT_YYYYMMDD.format(date);
    }

    public static String dateDvalue(Date date) {
        Long diff = date.getTime()-new Date().getTime();
        Long day,hour,secord,minute;
        String des = "";
        if(diff>0) {
            day = diff/(3600000*24);
            hour = diff%(3600000*24)/3600000;
            minute = diff%(3600000)/(1000*60);
            secord = diff%(60000)/1000;
            des = day==0?des:(des+day+"天");
            des = hour==0?des:(des+hour+"小时");
            des = minute==0?des:(des+minute+"分");
            des = secord==0?des:(des+secord+"秒");
        } else {
            des = "0";
        }
        return des;
    }

    /**
     * 环比日期计算
     * @param day
     * @return
     */
    public static String hbCalculate(String day) {
        day = day.replaceAll("-","");
        String year = (day.substring(0,4));
        String month = (day.substring(4,6));
        try {
            if(day.length()==6) { //月
                Date date = DateUtil.FORMAT_YYYY_MM.parse(year+"-"+month);
                Date lastMonth = DateUtil.calculate(date,Calendar.MONTH,-1);
                return DateUtil.FORMAT_YYYY_MM.format(lastMonth);
            } else if(day.length()==8) { //天
                Date date = DateUtil.FORMAT_YYYYMMDD.parse(day);
                Date lastDay = DateUtil.calculate(date,Calendar.DAY_OF_MONTH,-1);
                return DateUtil.FORMAT_YYYYMMDD.format(lastDay);
            }
        }catch (Exception e) {

        }
        return null;
    }
}